package com.jetinno.simple

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

/**
 * Created by zhangyuncai on 2021/11/11.
 */
abstract class SimpleActivity : FragmentActivity() {

    //方便打印日志的标签
    val TAG = this::class.java.simpleName

    //快捷注册EventBus
    var isRegisterEventBus = false

    fun getContext(): Context {
        return this
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if(!useDatabing()) {
            setContentView(getLayoutId())
        }
        if (isRegisterEventBus && !EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        initView()
        initEvent()
        initData()
    }

    protected open fun useDatabing(): Boolean {
        return false
    }

    protected abstract fun getLayoutId(): Int

    protected abstract fun initView()

    protected abstract fun initEvent()

    protected fun addOnClick(vararg ids: Int) {
        for (id in ids) {
            findViewById<View>(id).setOnClickListener { v -> onClick(v) }
        }
    }

    open fun onClick(v: View) {}

    protected abstract fun initData()

    /**
     * 延时一段时间收到消息
     * @param time 延时时间,毫秒
     * @param callback 延时时间已到回调
     */
    protected fun delayTime(time: Long, callback: ((Boolean) -> Unit)): Job {
        return lifecycleScope.launch {
            try {
                delay(time)
                callback.invoke(true)
            } catch (throwable: Throwable) {
                throwable.printStackTrace()
            }
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}
